package com.literature.search.core.utils;

import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import net.sourceforge.tess4j.util.ImageHelper;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 如果未将tessdata放在根目录下需要指定绝对路径
 * instance.setDatapath("the absolute path of tessdata");
 * @ClassName OCRUtil
 * @Description orc 离线识别
 * @Author
 * @Date
 * @Version 1.0
 **/
public class OcrUtil {
    // 存放在start子模块下的src/main/resources/tessdata
    // 去掉最前面的/
    private static final String TEST_RESOURCES_LANGUAGE_PATH = Thread.currentThread().getContextClassLoader().getResource("tessdata").getPath().substring(1);


    public static String parseText(String path) throws IOException, TesseractException {

        ITesseract instance = new Tesseract();

        instance.setDatapath(TEST_RESOURCES_LANGUAGE_PATH);

        //如果需要识别英文之外的语种，需要指定识别语种，并且需要将对应的语言包放进项目中
        instance.setLanguage("chi_sim");

        // 指定识别图片
        File file = new File(path);
        String ocrResult = "";
        if(file.exists()){
            BufferedImage img = ImageIO.read(file);
            // 处理图片
            img = processImage(img);
            //System.out.println(TEST_RESOURCES_LANGUAGE_PATH);
            ocrResult = instance.doOCR(img);
            ocrResult = PdfUtil.clearText(ocrResult);
        }
        return ocrResult;


    }


    /**
     * 处理图片
     * @param bufferedImage
     */
    public static BufferedImage processImage(BufferedImage bufferedImage) {
        // 这里对图片黑白处理,增强识别率.这里先通过截图,截取图片中需要识别的部分
        bufferedImage = ImageHelper.convertImageToGrayscale(bufferedImage);
        // 这里对图片进行二值化处理,增强识别率
        bufferedImage = ImageHelper.convertImageToBinary(bufferedImage);
        // 这里对图片进行放大处理,增强识别率
        bufferedImage = ImageHelper.getScaledInstance(bufferedImage, bufferedImage.getWidth() * 7, bufferedImage.getHeight() * 7);
        return bufferedImage;
    }


}
